package com.siyoumi.app.rabbitmq;

import com.rabbitmq.client.*;
import lombok.Getter;
import lombok.Setter;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.Connection;

//创建者
@Slf4j
public abstract class RabbitMqPublishAbs {
    @Getter
    private Channel channel;
    private Connection connection;

    abstract protected String getExchangeName();

    abstract protected String getQueueName();

    /**
     * 初始化
     */
    @SneakyThrows
    public void init() {
        CachingConnectionFactory factory = RabbitMqConfig.getConnectionFactory();
        //ConnectionFactory factory = new ConnectionFactory();
        //factory.setHost(config.getHost());
        //factory.setPort(config.getPort());
        //factory.setUsername(config.getUsername());
        //factory.setPassword(config.getPassword());
        //factory.setVirtualHost(config.getVhost());

        this.connection = factory.createConnection();
        this.channel = this.connection.createChannel(false);
    }

    /**
     * 发消息到队列
     *
     * @param message
     * @throws Exception
     */
    abstract public void publishMessage(RabbitMqMessage message);

    public void close() throws Exception {
        if (channel != null) {
            channel.close();
        }
        if (connection != null) {
            connection.close();
        }
    }
}